from Bases import ChildGroup
from basepage import BasePage
from .. import widgets


class CueStacks(BasePage):
    #button_size = dict(w=.15, h=.075)
    page_name = 'Cue Stacks'
    def __init__(self, **kwargs):
        self.current_stack = None
        super(CueStacks, self).__init__(**kwargs)
        self.num_stacks = kwargs.get('num_stacks', 8)
        self.button_size = dict(w=1./self.num_stacks, h=.075)
        
        bounds = [self.x_offset, self.y_offset, 1., self.button_size['h']]
        self.build_topwidget('Label', name='CueStacks', bounds=bounds)
        self.btn_topwidget = self.topwidget.add_widget(widgets.Label, value='Select Stack', name='select_buttons', bounds=bounds)
        self.SelectBtns = ChildGroup(name='select_buttons',
                                     osc_parent_node=self.osc_node)
                                          
        for x in range(1, self.num_stacks+1):
            btn = self.btn_topwidget.add_widget(CueStackSelBtn, Index=x, parent=self)
            self.SelectBtns.add_child(existing_object=btn)
            btn.bind(touch_state=self.on_SelectBtn_touch_state)
            
        self.topwidget.refresh_interface()
            
    @property
    def selected_index(self):
        return self._selected_index
    @selected_index.setter
    def selected_index(self, value):
        self._selected_index = value
        for btn in self.SelectBtns.itervalues():
            if btn.Index != value:
                #print btn.Index, btn.touch_state
                btn.touch_state = False
            #else:
            #    btn.selected = True
        stack = self.MainController.CueStacks.indexed_items.get(value)
        self.set_current_stack(stack)
        if len(self.SelectBtns) == 8:
            print [self.SelectBtns.indexed_items[i].touch_state for i in range(1, 9)]
            
    def set_current_stack(self, stack):
        if self.current_stack is not None:
            self.current_stack.remove()
            self.current_stack = None
        if stack is None:
            return
        bounds = self.topwidget.bounds[:]
        bounds[1] = bounds[1] + bounds[3]
        bounds[3] = 1. - (bounds[1] + self.button_size['h'])
        self.current_stack = self.topwidget.add_widget(StackControls, 
                                                       MainController=self.MainController, 
                                                       stack=stack, 
                                                       bounds=bounds)
                                                       
    def on_SelectBtn_touch_state(self, **kwargs):
        btn = kwargs.get('obj')
        state = kwargs.get('value')
        #print btn.Index, state
        if state:
            self.selected_index = btn.Index
        #for btn in self.SelectBtns.itervalues():
        #    btn.touch_state = state
            

class CueStackSelBtn(widgets.Toggle):
    def __init__(self, **kwargs):
        self._selected = False
        self.parent = kwargs.get('parent')
        self.MainController = self.parent.MainController
        self.CueStacks = self.MainController.CueStacks
        i = kwargs.get('Index')
        kwargs.setdefault('name', str(i))
        #kwargs.setdefault('osc_address', str(i))
        
        w = self.parent.button_size['w']
        h = self.parent.button_size['h']
        x = i * w - w
        y = 1. - h
        
        kwargs.setdefault('bounds', [x, y, w, h])
        #kwargs.setdefault('label', str(i))
        #kwargs.update(dict(foregroundColor=[255, 255, 255], backgroundColor=[32, 32, 32, 32], 
        #                   strokeColor=[255, 0, 0]))
        super(CueStackSelBtn, self).__init__(**kwargs)
        if self.Index is None:
            bob
#        lbl_kwargs = kwargs.copy()
#        bounds = lbl_kwargs.get('bounds')[:]
#        bounds[1] = bounds[1] + bounds[3] - .02
#        bounds[3] = .02
#        lbl_kwargs.update({'bounds':bounds, 'value':str(i), 'name':'indexlabel'})
#        lbl = self.add_widget(widgets.Label, **lbl_kwargs)
        
        self.current_stack = None
        stack = self.CueStacks.indexed_items.get(self.Index)
        if stack:
            self.set_current_stack(stack)
        self.CueStacks.bind(child_update=self.on_CueStack_child_update)
        
    def unlink(self):
        self.CueStacks.unbind(self)
        self.set_current_stack(None)
        super(CueStackSelBtn, self).unlink()
        
#    @property
#    def selected(self):
#        return self._selected
#    @selected.setter
#    def selected(self, value):
#        if value == self.selected:
#            return
#        self._selected = value
#        self.emit('selected_changed', obj=self, value=value)
        
    def set_current_stack(self, stack):
        if self.current_stack is not None:
            self.current_stack.unbind(self)
        if stack is None:
            self.label = ''
        else:
            self.label = stack.name
            stack.bind(name=self.on_stack_name_changed)
        self.current_stack = stack
        
    def on_stack_name_changed(self, **kwargs):
        self.label = kwargs.get('value')
        
    def on_CueStack_child_update(self, **kwargs):
        stack = self.CueStacks.indexed_items.get(self.Index)
        if stack != self.current_stack:
            self.set_current_stack(stack)
        
class StackControls(widgets.Label):
    num_cues = 10
    def __init__(self, **kwargs):
        kwargs['name'] = 'StackControls'
        super(StackControls, self).__init__(**kwargs)
        self.MainController = kwargs.get('MainController')
        self.stack = kwargs.get('stack')
        #self.cue_btns = ChildGroup(name='CueBtns', osc_parent_node=self.osc_node)
        self.cue_btns = {}
        btn_h = self.height / self.num_cues
        bkwargs = dict(x=self.x, width=self.width / 2., height=btn_h, stack=self.stack)
        for i in range(1, self.num_cues + 1):
            bkwargs.update(dict(y=self.y + (btn_h * (i-1)), index=i, name=str(i)))
            btn = self.add_widget(CueButton, **bkwargs)
            #self.cue_btns.add_child(existing_object=btn)
            self.cue_btns[i] = btn
        self.refresh_interface()

class CueButton(widgets.Toggle):
    def __init__(self, **kwargs):
        self.stack = kwargs.get('stack')
        self.cue = None
        self.index = kwargs.get('index')
        super(CueButton, self).__init__(**kwargs)
        self.set_cue(self.stack.Snapshots.indexed_items.get(self.index))
        self.stack.Snapshots.bind(child_update=self.on_Snapshots_child_update)
        
    def unlink(self):
        self.set_cue(None)
        self.stack.Snapshots.unbind(self)
        super(CueButton, self).unlink()
        
    def set_cue(self, cue):
        if self.cue is not None:
            self.cue.unbind(self)
            self.Property = None
        self.cue = cue
        if cue is not None:
            self.label = cue.name
            self.cue.bind(name=self.on_cuename_set)
            self.Property = (self.cue, 'active_prop')
            
    def on_Snapshots_child_update(self, **kwargs):
        cue = self.stack.Snapshots.indexed_items.get(self.index)
        if cue != self.cue:
            self.set_cue(cue)
            
    def on_cuename_set(self, **kwargs):
        self.label = self.cue.name
